import json
import random
from datetime import datetime

from django.shortcuts import render
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from user import models
from user import userser
from utils.tooljwt import tooljwt
# from .authentication import JWTAuthentication
from utils.authentication import JWTAuthenticationss
from utils.SendMessage import send_message
from utils.MyRedis import myredis


# Create your views here.

class UserRegister(APIView):
    def post(self, request):
        ser = userser.SerUser(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({"mes": "ok", "data": ser.data, "code": status.HTTP_201_CREATED})
        else:
            return Response({"mes": "error", "data": ser.errors, "code": status.HTTP_400_BAD_REQUEST})


class UsernameLogin(APIView):
    def post(self, request):
        username = request.data.get("username")
        password = request.data.get("password")
        data = models.UserModel.objects.filter(username=username, password=password).first()
        if data:
            token = tooljwt.gettoken({"id": data.id, "username": data.username})
            return Response({"msg": "ok", "data": {"id": data.id, "username": data.username, "token": token}})
        else:
            info = models.UserModel.objects.filter(username=username).first()
            if info:
                return Response({"msg": "密码错误"})
            else:
                return Response({"msg": "用户名错误"})


# class PhoneLogin(APIView):
#     def createdata(self, phone, code):
#         mycode = myredis.get_str(phone)
#         if mycode == code:
#             data = models.UserModel.objects.create(
#                 phone=phone, username=phone, password=123456, email=phone + "@qq.com")
#             if data:
#                 token = tooljwt.gettoken({"id": data.id})
#                 return Response({"msg": "ok", "data": {"id": data.id, "token": token}})
#
#     def post(self, request):
#         phone = request.data.get("phone")
#         code = request.data.get("code")
#         print(phone)
#         data = models.UserModel.objects.filter(phone=phone).first()
#         if data:
#             user_code = myredis.get_str(phone)
#             if code == user_code:
#                 token = tooljwt.gettoken({"id": data.id})
#                 return Response({"msg": "ok", "data": {"id": data.id, "token": token}})
#             else:
#                 return Response({"msg": "no"})
#         else:
#             self.createdata(phone, code)

class PhoneLogin(APIView):
    def post(self, request):
        phone = request.data.get("phone")
        code = request.data.get("code")
        mycode = myredis.get_str(phone)
        if code == mycode:
            data = models.UserModel.objects.filter(phone=phone).first()
            if not data:
                data = models.UserModel.objects.create(
                    phone=phone, username=phone, password=123456, email=phone + "@qq.com")
            token = tooljwt.gettoken({"id": data.id})
            return Response({"msg": "ok", "data": {"id": data.id, "token": token}})
        else:
            return Response({"msg": "验证码错误"})


class UserCenter(APIView):
    authentication_classes = (JWTAuthenticationss,)

    def get(self, request):
        return Response({"msg": "我是会员中心"})


class SendCode(APIView):
    def post(self, request):
        phone = request.data.get("phone")
        code = str(random.randint(1000, 9999))
        # res = json.loads(send_message(phone, code, 2))
        # if res['statusCode'] == '000000':
        #     myredis.set_time_str(phone, 60*2, code)
        #     return Response({"msg": "验证码发送成功"})
        # else:
        #     return Response({"msg": res['statusMsg']})

        if code:
            myredis.set_time_str(phone, 6000 * 2, code)
            return Response({"msg": "200", "code": code})
        else:
            return Response({"msg": "404"})


class UserCredit(APIView):
    authentication_classes = [JWTAuthenticationss]

    def get(self, request):
        user = request.query_params.get('user')
        data = models.UserModel.objects.filter(id=user).first()
        coudata = models.UserCoupon.objects.filter(user=user, isused=False, coupon__created_time__lte=datetime.now(), coupon__end_time__gte=datetime.now())
        ser = userser.UserCouponSer(coudata, many=True)
        return Response({"msg": "ok", "data": {"credit": data.score, "tomoney": 10, "coupon": ser.data}})
